//
//  WFlHotliveTableViewController.m
//  WangyiFangzuo
//
//  Created by 蔡靖方 on 16/9/12.
//  Copyright © 2016年 111. All rights reserved.
//
#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kDeviceVersion [[UIDevice currentDevice].systemVersion floatValue]
#define kNavbarHeight ((kDeviceVersion>=7.0)? 64 :44 )
#define kIOS7DELTA   ((kDeviceVersion>=7.0)? 20 :0 )

#define kTabBarHeight 49

#import "WFHeadview.h"
#import "WFlHotliveTableViewController.h"
#import <AFNetworking.h>
#import "WFmodelHot.h"
#import "WFhotTableViewCell.h"
#import "WFHeadmodel.h"
#import <UIImageView+WebCache.h>
#import "WFlableHeadmodel.h"
#import <MJRefresh.h>
#import "VideoCell.h"
//视频业
#import "DetailViewController.h"
#import "WMPlayer.h"
//视屏模型
#import "WFVideoModel.h"
#import <MJExtension.h>
//自定义刷新
#import "WFrefreshheaderHH.h"

@interface WFlHotliveTableViewController ()<WFHeadviewDelegate,UIScrollViewDelegate,WMPlayerDelegate>
@property (strong, nonatomic,) UIPageControl *pageControl;

@property(nonatomic,strong)UILabel *lablename;

@property(nonatomic,strong)NSMutableArray *arryM;

@property(nonatomic,strong)NSMutableArray *HeadarrM;
//下边为轮播器的控件
@property(nonatomic,strong)UIScrollView *scrollView;
@property (weak, nonatomic) NSTimer *timer;
@property (weak, nonatomic) NSTimer *timer1;
@property(nonatomic,strong)UIView *viewh;
@property(nonatomic,strong)NSMutableArray *lableHeadarrM;
@property(nonatomic,strong)UILabel *lableHead;
@property(nonatomic,strong)UIButton *buttonHead;
@property(nonatomic,strong)UILabel *lablenotice;
//视频
@property(nonatomic,assign)NSIndexPath *currentIndexPath;
@property(nonatomic,strong)VideoCell *currentCell;
@property(nonatomic,assign)BOOL isSmallScreen;
@property(nonatomic,strong)WMPlayer *wmPlayer;
@end

@implementation WFlHotliveTableViewController
- (void)viewDidLoad {
    [super viewDidLoad];

[self.tableView registerNib:[UINib nibWithNibName:@"VideoCell" bundle:nil] forCellReuseIdentifier:@"VideoCell"];
    //设置tabview的inset
    self.tableView.contentInset=UIEdgeInsetsMake(64, 0, 40, 0);
    [self refdata];

}

#pragma mark 下拉刷新
-(void)refdata{
    //自定义刷新
    self.tableView.mj_header=[WFrefreshheaderHH headerWithRefreshingBlock:^{
        [self updata];
    }];
    //    self.tableView.mj_header=[MJRefreshGifHeader headerWithRefreshingBlock:^{
//        NSLog(@"sd");
//        //请求数据
//        [self updata];
//    }];
  //  上拉加载更多
    MJRefreshAutoNormalFooter *foot=[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self Downdata];
    }];
    
        self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_footer=foot;


    [self.tableView.mj_header beginRefreshing];
    //设置mj的透明读
    self.tableView.mj_footer.automaticallyChangeAlpha=NO;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.arryM.count;
}

#pragma mark 穿件cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WFVideoModel *model=self.arryM[indexPath.row];
//    NSLog(@"%ld",self.arryM.count);
    static NSString *ID=@"VideoCell";
    VideoCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell=[[[NSBundle mainBundle]loadNibNamed:@"VideoCell" owner:nil options:nil]lastObject];
    }
    
    [cell.playBtn addTarget:self action:@selector(startPlayVideo:) forControlEvents:UIControlEventTouchUpInside];
    cell.playBtn.tag = indexPath.row;
    
    
    if (_wmPlayer&&_wmPlayer.superview) {
        if (indexPath.row==_currentIndexPath.row) {
            [cell.playBtn.superview sendSubviewToBack:cell.playBtn];
        }else{
            [cell.playBtn.superview bringSubviewToFront:cell.playBtn];
        }
        NSArray *indexpaths = [tableView indexPathsForVisibleRows];
        if (![indexpaths containsObject:_currentIndexPath]&&_currentIndexPath!=nil) {//复用
            
            if ([[UIApplication sharedApplication].keyWindow.subviews containsObject:_wmPlayer]) {
                _wmPlayer.hidden = NO;
            }else{
                _wmPlayer.hidden = YES;
                [cell.playBtn.superview bringSubviewToFront:cell.playBtn];
            }
        }else{
            if ([cell.backgroundIV.subviews containsObject:_wmPlayer]) {
                [cell.backgroundIV addSubview:_wmPlayer];
                
                [_wmPlayer play];
                _wmPlayer.hidden = NO;
            }
            
        }
    }

    cell.model=model;
    return cell;
}
#pragma mark 开始按钮
-(void)startPlayVideo:(UIButton *)sender{
    self.currentIndexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
    NSLog(@"currentIndexPath.row = %ld",_currentIndexPath.row);
    if ([UIDevice currentDevice].systemVersion.floatValue>=8||[UIDevice currentDevice].systemVersion.floatValue<7) {
        self.currentCell = (VideoCell *)sender.superview.superview;
    }else{//ios7系统 UITableViewCell上多了一个层级UITableViewCellScrollView
        self.currentCell = (VideoCell *)sender.superview.superview.subviews;
    }
    WFVideoModel *model = [self.arryM objectAtIndex:sender.tag];
//    NSLog(@"%@--------------",model.mp4_Hd_url);
    
    //    isSmallScreen = NO;
    if (self.isSmallScreen) {
        [self releaseWMPlayer];
        _isSmallScreen = NO;
        
    }
    if (_wmPlayer) {
        [self releaseWMPlayer];
        _wmPlayer = [[WMPlayer alloc]initWithFrame:self.currentCell.backgroundIV.bounds];
        _wmPlayer.delegate = self;
        _wmPlayer.closeBtnStyle = CloseBtnStyleClose;
        _wmPlayer.URLString = model.mp4_url;
        _wmPlayer.titleLabel.text = model.title;
//                [_wmPlayer play];
    }else{
        _wmPlayer = [[WMPlayer alloc]initWithFrame:self.currentCell.backgroundIV.bounds];
        _wmPlayer.delegate = self;
        _wmPlayer.closeBtnStyle = CloseBtnStyleClose;
        _wmPlayer.titleLabel.text = model.title;
        _wmPlayer.URLString = model.mp4_url;
    }
    [self.currentCell.backgroundIV addSubview:_wmPlayer];
    [self.currentCell.backgroundIV bringSubviewToFront:_wmPlayer];
    [self.currentCell.playBtn.superview sendSubviewToBack:self.currentCell.playBtn];
    [self.tableView reloadData];
    
}
///播放器事件
-(void)wmplayer:(WMPlayer *)wmplayer clickedCloseButton:(UIButton *)closeBtn{

    VideoCell *currentCell = (VideoCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndexPath.row inSection:0]];
    [currentCell.playBtn.superview bringSubviewToFront:currentCell.playBtn];
    [self releaseWMPlayer];
    [self setNeedsStatusBarAppearanceUpdate];
    
}
-(void)wmplayer:(WMPlayer *)wmplayer clickedFullScreenButton:(UIButton *)fullScreenBtn{
    if (fullScreenBtn.isSelected) {//全屏显示
        _wmPlayer.isFullscreen = YES;
        [self setNeedsStatusBarAppearanceUpdate];
        [self toFullScreenWithInterfaceOrientation:UIInterfaceOrientationLandscapeLeft];
    }else{
        if (_isSmallScreen) {
            //放widow上,小屏显示
            [self toSmallScreen];
        }else{
            [self toCell];
        }
    }
}
-(void)toSmallScreen{
    //放widow上
//    [_wmPlayer removeFromSuperview];
    [UIView animateWithDuration:0.5f animations:^{
        _wmPlayer.transform = CGAffineTransformIdentity;
        _wmPlayer.frame = CGRectMake(kScreenWidth/2,kScreenHeight-kTabBarHeight-(kScreenWidth/2)*0.75, kScreenWidth/2, (kScreenWidth/2)*0.75);
        _wmPlayer.playerLayer.frame =  _wmPlayer.bounds;
        [[UIApplication sharedApplication].keyWindow addSubview:_wmPlayer];
        [_wmPlayer.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wmPlayer).with.offset(0);
            make.right.equalTo(_wmPlayer).with.offset(0);
            make.height.mas_equalTo(40);
            make.bottom.equalTo(_wmPlayer).with.offset(0);
        }];
        [_wmPlayer.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wmPlayer).with.offset(0);
            make.right.equalTo(_wmPlayer).with.offset(0);
            make.height.mas_equalTo(40);
            make.top.equalTo(_wmPlayer).with.offset(0);
        }];
        [_wmPlayer.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wmPlayer.topView).with.offset(45);
            make.right.equalTo(_wmPlayer.topView).with.offset(-45);
            make.center.equalTo(_wmPlayer.topView);
            make.top.equalTo(_wmPlayer.topView).with.offset(0);
        }];
        [_wmPlayer.closeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wmPlayer).with.offset(5);
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(30);
            make.top.equalTo(_wmPlayer).with.offset(5);
            
        }];
        [_wmPlayer.loadFailedLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_wmPlayer);
            make.width.equalTo(_wmPlayer);
            make.height.equalTo(@30);
        }];
        
    }completion:^(BOOL finished) {
        _wmPlayer.isFullscreen = NO;
        [self setNeedsStatusBarAppearanceUpdate];
        _wmPlayer.fullScreenBtn.selected = NO;
        _isSmallScreen = YES;
        [[UIApplication sharedApplication].keyWindow bringSubviewToFront:_wmPlayer];
    }];
    
}



-(void)toCell{
    VideoCell *currentCell = (VideoCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndexPath.row inSection:0]];
    [_wmPlayer removeFromSuperview];
//    NSLog(@"row = %ld",_currentIndexPath.row);
    [UIView animateWithDuration:0.5f animations:^{
        _wmPlayer.transform = CGAffineTransformIdentity;
        _wmPlayer.frame = currentCell.backgroundIV.bounds;
        _wmPlayer.playerLayer.frame =  _wmPlayer.bounds;
        [currentCell.backgroundIV addSubview:_wmPlayer];
        [currentCell.backgroundIV bringSubviewToFront:_wmPlayer];
        [_wmPlayer.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wmPlayer).with.offset(0);
            make.right.equalTo(_wmPlayer).with.offset(0);
            make.height.mas_equalTo(40);
            make.bottom.equalTo(_wmPlayer).with.offset(0);
        }];
        [_wmPlayer.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wmPlayer).with.offset(0);
            make.right.equalTo(_wmPlayer).with.offset(0);
            make.height.mas_equalTo(40);
            make.top.equalTo(_wmPlayer).with.offset(0);
        }];
        [_wmPlayer.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wmPlayer.topView).with.offset(45);
            make.right.equalTo(_wmPlayer.topView).with.offset(-45);
            make.center.equalTo(_wmPlayer.topView);
            make.top.equalTo(_wmPlayer.topView).with.offset(0);
        }];
        [_wmPlayer.closeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_wmPlayer).with.offset(5);
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(30);
            make.top.equalTo(_wmPlayer).with.offset(5);
        }];
        [_wmPlayer.loadFailedLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_wmPlayer);
            make.width.equalTo(_wmPlayer);
            make.height.equalTo(@30);
        }];
    }completion:^(BOOL finished) {
        _wmPlayer.isFullscreen = NO;
        [self setNeedsStatusBarAppearanceUpdate];
        _isSmallScreen = NO;
        _wmPlayer.fullScreenBtn.selected = NO;
        
    }];
    
}

-(void)toFullScreenWithInterfaceOrientation:(UIInterfaceOrientation )interfaceOrientation{
    [_wmPlayer removeFromSuperview];
    //竖屏横屏

    _wmPlayer.transform = CGAffineTransformIdentity;
    if (interfaceOrientation==UIInterfaceOrientationLandscapeLeft) {
        _wmPlayer.transform = CGAffineTransformMakeRotation(-M_PI_2);
    }else if(interfaceOrientation==UIInterfaceOrientationLandscapeRight){
        _wmPlayer.transform = CGAffineTransformMakeRotation(M_PI_2);
    }
    
    
    _wmPlayer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    _wmPlayer.playerLayer.frame =  CGRectMake(0,0, kScreenHeight,kScreenWidth);
    
    [_wmPlayer.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(kScreenWidth-40);
        make.width.mas_equalTo(kScreenHeight);
    }];
    
    [_wmPlayer.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(40);
        make.left.equalTo(_wmPlayer).with.offset(0);
        make.width.mas_equalTo(kScreenHeight);
    }];
    
    [_wmPlayer.closeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_wmPlayer).with.offset((-kScreenHeight/2));
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(30);
        make.top.equalTo(_wmPlayer).with.offset(5);
        
    }];
    
    [_wmPlayer.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_wmPlayer.topView).with.offset(45);
        make.right.equalTo(_wmPlayer.topView).with.offset(-45);
        make.center.equalTo(_wmPlayer.topView);
        make.top.equalTo(_wmPlayer.topView).with.offset(0);
    }];
    
    [_wmPlayer.loadFailedLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenHeight);
        make.center.mas_equalTo(CGPointMake(kScreenWidth/2-36, -(kScreenWidth/2)));
        make.height.equalTo(@30);
    }];
    
    [_wmPlayer.loadingView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(CGPointMake(kScreenWidth/2-37, -(kScreenWidth/2-37)));
    }];
    [_wmPlayer.loadFailedLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenHeight);
        make.center.mas_equalTo(CGPointMake(kScreenWidth/2-36, -(kScreenWidth/2)+36));
        make.height.equalTo(@30);
    }];
    [[UIApplication sharedApplication].keyWindow addSubview:_wmPlayer];
    
    _wmPlayer.fullScreenBtn.selected = YES;
    [_wmPlayer bringSubviewToFront:_wmPlayer.bottomView];
    
}

-(void)wmplayer:(WMPlayer *)wmplayer singleTaped:(UITapGestureRecognizer *)singleTap{

}
-(void)wmplayer:(WMPlayer *)wmplayer doubleTaped:(UITapGestureRecognizer *)doubleTap{

}

///播放状态
-(void)wmplayerFailedPlay:(WMPlayer *)wmplayer WMPlayerStatus:(WMPlayerState)state{

}
-(void)wmplayerReadyToPlay:(WMPlayer *)wmplayer WMPlayerStatus:(WMPlayerState)state{

}
-(void)wmplayerFinishedPlay:(WMPlayer *)wmplayer{

    VideoCell *currentCell = (VideoCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndexPath.row inSection:0]];
    [currentCell.playBtn.superview bringSubviewToFront:currentCell.playBtn];
    [self releaseWMPlayer];
    [self setNeedsStatusBarAppearanceUpdate];
}

/**
 *  释放WMPlayer
 */
-(void)releaseWMPlayer{
    [_wmPlayer.player.currentItem cancelPendingSeeks];
    [_wmPlayer.player.currentItem.asset cancelLoading];
    [_wmPlayer pause];
    
    
    [_wmPlayer removeFromSuperview];
    [_wmPlayer.playerLayer removeFromSuperlayer];
    [_wmPlayer.player replaceCurrentItemWithPlayerItem:nil];
    _wmPlayer.player = nil;
    _wmPlayer.currentItem = nil;
    //释放定时器，否侧不会调用WMPlayer中的dealloc方法
    [_wmPlayer.autoDismissTimer invalidate];
    _wmPlayer.autoDismissTimer = nil;
    
    
   _wmPlayer.playOrPauseBtn = nil;
    _wmPlayer.playerLayer = nil;
    _wmPlayer = nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 260;
    
}
//刷新数据
-(void)updata{
        AFHTTPSessionManager *mager=[AFHTTPSessionManager manager];
        NSString *url=@"http://data.live.126.net/livechannel/previewlist.json";

        [mager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self.HeadarrM removeAllObjects];
            for (NSDictionary *dict in responseObject[@"top"]) {
                WFHeadmodel *model=[WFHeadmodel WFHeadWithdict:dict];
                [self.HeadarrM addObject:model];

            }
            [self.lableHeadarrM removeAllObjects];
            for (NSDictionary *dict in responseObject[@"future"]) {
                WFlableHeadmodel *model=[WFlableHeadmodel WFlableWithdict:dict];
                [self.lableHeadarrM addObject:model];
            }
            //添加头部视图
            [self createInfiniteScrollView];
            
            //添加轮播器下方的lable
            [self addlable];
            NSRunLoop *runloop=[NSRunLoop mainRunLoop];
            
            _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(addlable) userInfo:nil repeats:YES];
            [runloop addTimer:_timer forMode:NSRunLoopCommonModes];
//            NSLog(@"%ld----",self.arryM.count);
//          NSLog(@"%ld",self.HeadarrM.count);
        

            [self.tableView reloadData];

            

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
    //视频请求数据；；
    
    AFHTTPSessionManager *magerVi=[AFHTTPSessionManager manager];
    NSString *urlVi=@"http://c.3g.163.com/nc/video/list/VAP4BFE3U/y/0-10.html";
    [magerVi GET:urlVi parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.arryM=[WFVideoModel mj_objectArrayWithKeyValuesArray:responseObject[@"VAP4BFE3U"]];
//        NSLog(@"%@",self.arryM);
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [self.tableView.mj_header endRefreshing];

    }];


}
#pragma mark 加载更多数据
-(void)Downdata{
    AFHTTPSessionManager *mager=[AFHTTPSessionManager manager];

    
   // NSString *url=@"http://data.live.126.net/livechannel/previewlist.json";
   
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/video/list/VAP4BFE3U/y/%ld-10.html",self.arryM.count - self.arryM.count%10];
    [mager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //self.arryM=responseObject[@"live_review"];
        
        
        NSMutableArray *arryTemp=[NSMutableArray array];
            arryTemp=[WFVideoModel mj_objectArrayWithKeyValuesArray:responseObject[@"VAP4BFE3U"]];
            
        [self.arryM addObjectsFromArray:arryTemp];
        
        
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_footer endRefreshing];
        NSLog(@"%@",error);
    }];
    


    
}
//
//-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return 10;
//    
//    }
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    if (section==0) {
//        return 5;
//    }else{
//        return 0;
//    }
//}
#pragma mark 轮播器
//创建顶部的轮播图
- (void)createInfiniteScrollView {

//    NSLog(@"%ld",self.HeadarrM.count);
    _viewh=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 230)];

    self.tableView.tableHeaderView=_viewh;
//    _scrollView.frame = CGRectMake(0, 20, self.view.frame.size.width, 170);
    _scrollView = [[UIScrollView alloc] init];
    
//    scrollView.backgroundColor=[UIColor blackColor];
    _scrollView.frame=CGRectMake(0, 0, self.view.frame.size.width, 170);
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
//    scrollView.delegate = self;
    _scrollView.contentSize=CGSizeMake((self.HeadarrM.count)*_scrollView.frame.size.width, 0);
//    self.tableView.tableHeaderView=scrollView;
//    self.tableView.tableHeaderView.frame=CGRectMake(0, 0, 414, 300);
    _scrollView.delegate=self;
    [_viewh addSubview:_scrollView];
    
    
    // 页码视图
    _pageControl = [[UIPageControl alloc] init];
    CGFloat pageW = 80;
    CGFloat pageH = 20;
    // 设置页码
    self.pageControl.numberOfPages = self.HeadarrM.count;
    self.pageControl.currentPage = 0;
    
    CGFloat pageX = _scrollView.frame.size.width - pageW;
    CGFloat pageY = _scrollView.frame.size.height - pageH;
    self.pageControl.frame = CGRectMake(pageX, pageY, pageW, pageH);
    
    _pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    [self.tableView.tableHeaderView addSubview:_pageControl];
    
    
    _lablename=[[UILabel alloc]init];

    [_lablename setTextColor:[UIColor whiteColor]];
    self.lablename.frame=CGRectMake(0, pageY, _scrollView.frame.size.width-pageW, pageH);
    [self.tableView.tableHeaderView addSubview:_lablename];
    // 图片控件
    for (int i = 0; i<self.HeadarrM.count; i++) {
        WFHeadmodel *model=self.HeadarrM[i];
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectMake(i*_scrollView.frame.size.width,0, _scrollView.frame.size.width, _scrollView.frame.size.height);
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.image]];
        _lablename.text=model.roomName;
        [_scrollView addSubview:imageView];

        
    }
    

    _timer1 = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(next) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer1 forMode:NSRunLoopCommonModes];


}

#pragma mark 监听scrollView正在滚动

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //获取scrollView在X轴上的偏移量  因为scrollView每偏移一个图片宽度pagecontrol的当前页就要更换
    CGFloat w = self.scrollView.contentOffset.x;
    int num = w/self.scrollView.frame.size.width;
    if (num<self.HeadarrM.count) {
        WFHeadmodel *model=self.HeadarrM[num];
        _lablename.text=model.roomName;

    }
            //当前页跟谁scrollView偏移的距离来更换
    self.pageControl.currentPage = num;
    
    
    
            //视频的tableview的滚动
    if(scrollView ==self.tableView){
        if (_wmPlayer==nil) {
            return;
        }

        if (_wmPlayer.superview) {
            CGRect rectInTableView = [self.tableView rectForRowAtIndexPath:_currentIndexPath];
            CGRect rectInSuperview = [self.tableView convertRect:rectInTableView toView:[self.tableView superview]];
            if (rectInSuperview.origin.y<-self.currentCell.backgroundIV.frame.size.height) {//往上拖动
                
                if ([[UIApplication sharedApplication].keyWindow.subviews containsObject:_wmPlayer]&&_isSmallScreen) {
                    _isSmallScreen = YES;
                }else{
                    //放widow上,小屏显示
                    [self toSmallScreen];
                }
                
            }else{
                if ([self.currentCell.backgroundIV.subviews containsObject:_wmPlayer]) {
                    
                }else{
                    [self toCell];
                }
            }
        }
        
    }

}

-(void)next{
    //获取当前页数
    long  int num = self.pageControl.currentPage;
//    NSLog(@"%ld",self.pageControl.currentPage);
    if (num == self.HeadarrM.count-1) {
        num = 0;
    }else{
        num++;
    }
    //要想实现偏移 就要告诉scrollView的contentOffset的偏移量
    self.scrollView.contentOffset = CGPointMake(num*self.scrollView.frame.size.width, 0);
}
#pragma mark lable滚动
-(void)addlable{
    static long int i=0;
        WFlableHeadmodel *model=self.lableHeadarrM[i];
    self.lableHead.text=model.roomName;
    _lableHead.frame=CGRectMake(60,self.scrollView.frame.size.height, self.scrollView.frame.size.width-120, 50);

    [_viewh addSubview:_lableHead];
    
    if (i==self.lableHeadarrM.count-1) {
        i=0;
    }else{
        i++;
    }
    //穿件场次的按钮
    self.buttonHead.frame=CGRectMake(CGRectGetMaxX(self.lableHead.frame), self.scrollView.frame.size.height, 50, 50);
    [_buttonHead setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_buttonHead setTitle:[NSString stringWithFormat:@"%ld  场",self.arryM.count] forState:UIControlStateNormal];
    _buttonHead.enabled=YES;
    
    [_viewh addSubview:_buttonHead];
//穿件预告
    self.lablenotice.frame=CGRectMake(0, CGRectGetMaxY(self.scrollView.frame), 60, 50);
    [_lablenotice setTextColor:[UIColor blueColor]];
    _lablenotice.text=@"预告 /";
    [_viewh addSubview:_lablenotice];
    
}
#pragma mark  结束定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.timer invalidate];
    [_timer1 invalidate];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DetailViewController  *Vide=[[DetailViewController alloc]init];
    
    
    WFVideoModel *   model = self.arryM[indexPath.row];
    
    
    Vide.URLString  = model.m3u8_url;
    Vide.title = model.title;
    
    [self.navigationController pushViewController:Vide animated:YES];
    
    
}
//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
//    NSRunLoop *runloop=[NSRunLoop mainRunLoop];
//    
//    _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(addlable) userInfo:nil repeats:YES];
//    [runloop addTimer:_timer forMode:NSRunLoopCommonModes];
//    _timer1 = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(next) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop] addTimer:_timer1 forMode:NSRunLoopCommonModes];
//}

#pragma mark - JGInfiniteScrollViewDelegate -

- (void)ScrollViewDidClickAtAnyImageView:(UIImageView *)imageView {
    
    NSLog(@"%ld --  %@",imageView.tag, imageView.image);
    
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(NSMutableArray *)lableHeadarrM{
    if (!_lableHeadarrM) {
        _lableHeadarrM=[NSMutableArray array];
    }
    return _lableHeadarrM;
}
-(NSMutableArray *)arryM{
    if (!_arryM) {
        _arryM=[[NSMutableArray alloc]init];
    }
    return _arryM;
}
-(NSMutableArray *)HeadarrM{
    if (!_HeadarrM) {
        _HeadarrM=[NSMutableArray array];
    }
    return _HeadarrM;
}
-(UILabel *)lableHead{
    if (!_lableHead) {
        _lableHead=[[UILabel alloc]init];
    }
    return _lableHead;
}
-(UIButton *)buttonHead{
    if (!_buttonHead) {
        _buttonHead=[[UIButton alloc]init];
    }
    return _buttonHead;
}
-(UILabel *)lablenotice{
    if (!_lablenotice) {
        _lablenotice=[[UILabel alloc]init];
    }
    return _lablenotice;
}
-(void)dealloc{
    NSLog(@"%@ dealloc",[self class]);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self releaseWMPlayer];
}

@end
